package utils.wechat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import vos.weChat.TokenVo;

public class HttpUtil {
	/**
	 * http的GET请求
	 *
	 * @Title: doGet 
	 * @param url
	 * @return
	 * @return: String
	 */
	public static String doGet(String url){
		try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();    
              
            http.setRequestMethod("GET");      //必须是get方式请求    
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");    
            http.setDoOutput(true);        
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
            http.connect();
            InputStream is =http.getInputStream();
            int size =is.available();
            byte[] jsonBytes =new byte[size];
            is.read(jsonBytes);
            String message=new String(jsonBytes,"UTF-8");
            return message;
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
       return "";
}
	/**
	 * POST请求
	 *
	 * @Title: doPost 
	 * @param action
	 * @param json 传输的json串
	 * @return
	 * @return: String
	 */
	public static String doPost(String action,String json){
		try {
	           URL url = new URL(action);
	           HttpURLConnection http =   (HttpURLConnection) url.openConnection();    
	           http.setRequestMethod("POST");        
	           http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");    
	           http.setDoOutput(true);        
	           http.setDoInput(true);
	           System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
	           System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
	 
	           http.connect();
	           OutputStream os= http.getOutputStream();    
	           os.write(json.getBytes("UTF-8"));//传入参数    
	           os.flush();
	           os.close();
	         
	           InputStream is =http.getInputStream();
	           int size =is.available();
	           byte[] jsonBytes =new byte[size];
	           is.read(jsonBytes);
	           String message=new String(jsonBytes,"UTF-8");
	           return message;
       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
		return "";
	}
}
